<%@ page import="com.party.core.model.system.TargetType" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="../../include/tag.jsp" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <title>${mallGoods.id == null ? '发布' : '编辑'}商品</title>
    <%@include file="../../include/commonFile.jsp" %>
    <link rel="stylesheet" href="${ctx}/css/common/list.css">
    <link rel="stylesheet" href="${ctx}/css/common/img_text.css">
    <link rel="stylesheet" href="${ctx}/static/uploadCI/upload.css">
    <link rel="stylesheet" href="${ctx}/css/ui/activity/publish_form.css">
    <link rel="stylesheet" href="${ctx}/css/ui/mall/goods_form.css">
    <link rel="stylesheet" href="${ctx}/css/form-preview.css">
</head>
<body>
<!--头部-->
<%@include file="../../include/header.jsp" %>
<div class="index-outside">
    <%@include file="../../include/sidebar.jsp" %>
    <!--内容-->
    <section>
        <div class="section-main">
            <!-- 正文请写在这里 -->
            <div class="add-form-content">
                <form id="myForm" class="layui-form mt20" method="post" action="${ctx}/mall/goods/save.do">
                    <div class="preview-box">
                        <div class="top-tip">
                            <span class="tip-inner"><span class="tip-title">效果预览</span></span>
                        </div>
                        <a class="preview-btn layui-btn layui-btn-danger layui-btn-sm" href="javascript:void(0)"
                           lay-submit lay-filter="*">
                            <i class="iconfont icon-refresh btn-icon"></i>预览
                        </a>
                        <iframe style="width: 360px;height: 760px;" frameborder="0"
                                src="${ctx}/phone/preview.do?url=/shop/goods/preview?id=${mallGoods.id}"></iframe>
                    </div>
                    <div class="form-outer">
                        <div id="hiddenCacheDiv">
                            <input type="hidden" name="categoryCache"/>
                            <input type="hidden" name="specModelCache"/>
                            <input type="hidden" name="productCache"/>
                        </div>
                        <fieldset class="border mb10">
                            <legend>商品信息</legend>
                            <div class="form-inner">
                                <input type="hidden" name="id" value="${mallGoods.id}"/>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">商品名称<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-block">
                                        <input type="text" name="name" lay-verify="name" autocomplete="off" placeholder="商品名称"
                                               lay-verify="name" class="layui-input" value="${mallGoods.name}" maxlength="50"
                                               style="float: left; margin-right: 10px; width: calc(100% - 110px);"
                                        >
                                        <div class="layui-form-mid layui-word-aux">最多50字符</div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">商品品牌<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-inline">
                                        <select name="brandId" lay-verify="brandId">
                                            <option value="">请选择商品品牌</option>
                                            <c:forEach var="brand" items="${goodsBrands}">
                                                <option value="${brand.id}" ${mallGoods.brandId == brand.id ? 'selected' : ''} ${brandId == brand.id ? 'selected' : ''}>${brand.name}</option>
                                            </c:forEach>
                                        </select>
                                    </div>
                                    <div class="layui-form-mid layui-word-aux"><a href="${ctx}/mall/brand/list.do" class="red">新增品牌</a></div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">商品图片<span class="f-verify-red">*</span></label>
                                    <button class="layui-btn layui-btn-danger addPicBtn" type="button" onclick="openUploadCI()">
                                        <i class="iconfont icon-add btn-icon"></i> 添加图片
                                    </button>
                                    <div class="form-word-aux">建议尺寸：750×750 可以拖拽图片调整顺序 最多上传10张</div>
                                    <div class="layui-input-block" style="min-height: auto;">
                                        <input type="hidden" name="picList" id="picList" lay-verify="picList" value="${pics}"/>
                                        <div class="zc-ci-img-list ci-img-list" id="img_list">
                                            <c:forEach var="resource" items="${picList}">
                                                <div class="item" data-url="${resource.url}">
                                                    <div class="img-item" style="background-image: url('${resource.url}')">
                                                        <span class="icon-close-new" style="right: -11px; top: -13px;"
                                                              onclick="delQImg(this)"></span>
                                                    </div>
                                                </div>
                                            </c:forEach>
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">主图视频</label>
                                    <div class="layui-input-block">
                                        <input type="hidden" name="videoList" id="videoList"/>
                                        <div style="margin-bottom: 10px;">
                                            <textarea class="layui-textarea video-link margin-right calc-110"
                                                      readonly
                                                      style="min-height: 80px;"
                                                      id="vide_code">${video.url}</textarea>
                                            <a href="javascript:openUploadVideo()" class="red" style="display: inline-block; margin-bottom: 5px">添加视频</a>
                                            <a href="javascript:clearValue()" class="red" style="display: inline-block">清除视频</a>
                                            <div class="cl"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </fieldset>
                        <fieldset class="border mb10">
                            <legend>价格库存</legend>
                            <div class="form-inner" style="margin-right: 10px">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">商品分类<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-block">
                                        <input type="hidden" name="categoryList" id="categoryIds" value=""
                                               lay-verify="categoryId"/>
                                        <div class="tag-wrap">
                                            <c:forEach var="category" items="${categoryList}">
                                                <div class="tag-item" data-id="${category.id}">
                                                    <span class="tag-name">${category.name}</span>
                                                    <i class="iconfont icon-close category-opt"></i>
                                                </div>
                                            </c:forEach>
                                        </div>
                                        <a href="javascript:selectCategory();" class="layui-btn layui-btn-danger addCategoryBtn" style="float: left; margin-right: 10px;" >
                                            <i class="iconfont icon-add btn-icon"></i>
                                            选择分类
                                        </a>
                                        <div class="layui-form-mid layui-word-aux"><a href="${ctx}/mall/category/list.do" class="red">新增分类</a></div>
                                        <i class="cl"></i>
                                    </div>
                                </div>
                                <%@include file="../goods/specInclude.jsp" %>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">价格<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-inline">
                                        <input type="text" class="layui-input" lay-verify="price" name="price"
                                               value="${mallGoods.price}" ${hasSpec ? 'readonly' : ''} />
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">总库存<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-inline">
                                        <input type="text" class="layui-input" lay-verify="stock" name="stock" data-stock="${mallGoods.stock}"
                                               value="${mallGoods.stock}" ${hasSpec ? 'readonly' : ''} />
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">剩余库存<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-inline">
                                        <input type="text" class="layui-input realStock" value="${mallGoods.realStock}" readonly />
                                    </div>
                                    <%--<div class="layui-form-mid layui-word-aux">
                                        <input type="checkbox" name="showStock" lay-filter="showStock" value="${mallGoods.showStock}" lay-skin="primary"
                                        ${mallGoods.showStock ? 'checked' : ''}
                                               title="页面不显示剩余件数"/>
                                    </div>--%>
                                    <div class="layui-form-mid layui-word-aux cl" style="margin-left: 130px;">
                                        剩余库存为0时，会放到【已售罄】的商品列表，发布后买家看到的商品可售库存同步更新
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">原价<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-inline">
                                        <input type="text" class="layui-input" name="originalPrice" lay-verify="originalPrice"
                                               value="${mallGoods.originalPrice}"/>
                                    </div>
                                    <div class="layui-form-mid layui-word-aux">在商品详情会以划线形式显示</div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">成本价<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-inline">
                                        <input type="text" class="layui-input" name="costPrice" value="${mallGoods.costPrice}"
                                               lay-verify="costPrice" ${hasSpec ? 'readonly' : ''}
                                        />
                                    </div>
                                    <div class="layui-form-mid layui-word-aux">成本价未来会用于营销建议，利润分析等</div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">批发价<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-inline">
                                        <input type="text" class="layui-input" name="tradePrice" value="${mallGoods.tradePrice}"
                                               lay-verify="tradePrice" ${hasSpec ? 'readonly' : ''}
                                        />
                                    </div>
                                    <div class="layui-form-mid layui-word-aux">批发价用于给机构结算</div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">商品编码</label>
                                    <div class="layui-input-inline">
                                        <input type="text" class="layui-input" name="number" value="${mallGoods.number}"/>
                                    </div>
                                </div>
                            </div>
                        </fieldset>
                        <fieldset class="border mb10">
                            <legend>其他信息</legend>
                            <div class="form-inner">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">运费设置<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-block">
                                        <div>
                                            <input type="radio" class="radio_yes" title="统一邮费" checked />
                                            <input class="layui-input" type="number" name="postage"
                                                   lay-verify="postage" placeholder="0.00" value='<fmt:formatNumber value="${mallGoods.postage}" pattern="0.00"/>'
                                                   style="vertical-align: unset; width: 150px; display: inline-block; height: 30px;"
                                            >
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">上架时间<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-block">
                                        <div>
                                            <input type="radio" class="radio_yes" name="openStatus" lay-filter="openStatus"
                                                   lay-verify="openStatus"
                                                   value="1" title="立即上架售卖"
                                                   <c:if test="${empty mallGoods.id}">checked</c:if>
                                                   <c:if test="${mallGoods.status == 1 && empty mallGoods.openStartTime}">checked</c:if>
                                            />
                                        </div>
                                        <div>
                                            <input type="radio" class="radio_zdy" name="openStatus" lay-filter="openStatus"
                                                   lay-verify="openStatus"
                                                   value="2" title="自定义上架时间"
                                                   <c:if test="${mallGoods.status == 1 && not empty mallGoods.openStartTime}">checked</c:if>
                                            />
                                            <input class="layui-input" type="text" name="openStartDate"
                                                   lay-verify="openStartDate"
                                                   placeholder="请选择上架售卖时间" readonly
                                                   value="<fmt:formatDate value="${mallGoods.openStartTime}" pattern="yyyy-MM-dd HH:mm"/>"
                                                   style="vertical-align: unset; width: 150px; display: inline-block; height: 30px;"
                                            >
                                        </div>
                                        <div>
                                            <input type="radio" class="radio_no" name="openStatus" lay-filter="openStatus"
                                                   value="3"
                                                   lay-verify="openStatus"
                                                   <c:if test="${mallGoods.status == 2 && empty mallGoods.openStartTime}">checked</c:if>
                                                   title="暂不售卖，放入仓库"/>
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">积分购买</label>
                                    <div>
                                        <div>
                                            <input type="radio" class="radio_yes" name="type" value="2"
                                                   <c:if test="${mallGoods.type == 2 && not empty mallGoods.type}">checked</c:if>
                                                   title="是"/>
                                            <input type="radio" class="radio_no" name="type" value="1"
                                                   <c:if test="${mallGoods.type == 1 || empty mallGoods.type}">checked</c:if>
                                                   title="否"/>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </fieldset>
                        <fieldset class="border mb10">
                            <legend>商品详情</legend>
                            <div class="form-inner" style="margin-right: 10px">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">商品简介</label>
                                    <div class="layui-input-block">
                                        <textarea name="remarks" class="layui-textarea"
                                                  placeholder="当用户通过微信将这件商品推荐给朋友时会显示出商品的简介，想想怎么编辑这段话吧~">${mallGoods.remarks}</textarea>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">商品详情<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-block">
                                        <script id="ueditor1" type="text/plain"></script>
                                        <div style="display: none" id="contentView">${goodsDetail.content}</div>
                                        <input type="hidden" name="content" id="content" lay-verify="content" data-link-ue="ueditor1" />
                                    </div>
                                </div>
                            </div>
                        </fieldset>
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <a href="javascript:void(0)" class="layui-btn layui-btn-danger" lay-submit
                                   lay-filter="*">立即提交</a>
                                <a href="${ctx}/mall/goods/list.do" class="layui-btn layui-btn-primary">取消</a>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div><!--底部-->
        <%@include file="../../include/footer.jsp" %>
    </section>
</div>

<script type="text/javascript" src="${ctx}/script/common/form_cache.js"></script>

<script type="text/javascript" src="${ctxStatic}/UEditor/ueditor.config.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/ueditor.all.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/myplugin/uploadCI.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/myplugin/uploadVideo.js"></script>
<!--建议手动加在语言，避免在ie下有时因为加载语言失败导致编辑器加载失败-->
<!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型，比如你在配置项目里配置的是英文，这里加载的中文，那最后就是中文-->
<script type="text/javascript" src="${ctxStatic}/UEditor/lang/zh-cn/zh-cn.js"></script>
<script src="${ctx}/script/form/jquery-1.12.4.js"></script>
<script src="${ctx}/script/form/jquery-ui.js"></script>
<script>
    txz.initHeader({
        nav: [{
            name: '商品管理',
            href: '${ctx}/mall/goods/list.do'
        }, {
            name: '${mallGoods.id == null ? '发布' : '编辑'}商品',
            curr: true
        }],
        btns: [{
            type: 'back'
        }]
    });

    var maxNum = 10;
    
    var ue = UE.getEditor('ueditor1', {
        initialFrameHeight: 500,//设置编辑器高度
        scaleEnabled: true
    });
    var form, laydate, formcache;
    $(function () {
        layui.use(['form', 'laydate'], function () {
            form = layui.form, laydate = layui.laydate;

            // 查询发布日期
            var start = {
                elem: 'input[name=openStartDate]',
                min: new Date().Format("yyyy-MM-dd HH:mm:ss"),
                type: 'datetime',
                format: 'yyyy-MM-dd HH:mm',
                done: function (value, date, endDate) {
                    if (date != null) {
                        var date = new Date();
                        var start = new Date(value.replace(/-/g, "/"));
                        if (start < date) {
                            util.layerMsgError("上架时间不能早于今天");
                            return false;
                        }
                        $("[name=openStatus]").prop("checked", false);
                        $(".radio_zdy").prop("checked", true);
                        form.render('radio');
                    }
                }
            };
            laydate.render(start);

            form.render('radio');
            form.render('select');

            txzSpec.init('${results}');

            form.on('radio(openStatus)', function (data) {
                if (data.value == 1 || data.value == 3) {
                    $("[name=openStartDate]").val("");
                }
            });

            form.on('checkbox(showStock)', function (data) {
                var chk = data.elem.checked;
                if (chk) {
                    $("[name=showStock]").val(true);
                } else {
                    $("[name=showStock]").val(false);
                }
            });

            //自定义验证规则
            form.verify({
                name: function (value) {
                    if (value.trim() == "") {
                        return '商品名不能为空';
                    }
                },
                brandId: function (value) {
                    if (value == "") {
                        return "请选择品牌";
                    }
                },
                picList: function (value) {
                    var array = new Array();
                    $("#img_list .item").each(function (index, element) {
                        array.push($(element).attr("data-url"));
                    });
                    if (array.length == 0) {
                        return "请上传图片";
                    } else if (array.length > maxNum) {
                        return "最多只允许上传" + maxNum + "张图片";
                    }
                },
                categoryId: function (value) {
                    var length = $(".tag-item").length;
                    if (length == 0) {
                        return "请选择分类";
                    }
                },
                price: function (value) {
                    var length = $("#myTable tbody").find(".tr-data").length;
                    if (value.trim() == "") {
                        return "价格不能为空";
                    } else if (length == 0) {
                        if (!util.checkPrice(value)) {
                            return "请输入一个正确的价格";
                        } else if (parseFloat(value) == 0) {
                            return "请输入大于0的金额";
                        }
                    }
                },
                stock: function (value) {
                    if (value.trim() == "") {
                        return "库存不能为空";
                    } else if (!util.checkNumber(value)) {
                        return "请输入一个正确的库存";
                    }
                    <%--if (${not empty mallGoods.id}) {--%>
                    //     var stock = $("[name=stock]").data('stock');
                    //     if (value < stock) {
                    //         return "库存不能低于原库存：" + stock;
                    //     }
                    // }
                },
                originalPrice: function (value) {
                    if (value.trim() == '') {
                        return "原价不能为空";
                    }
                },
                costPrice : function (value) {
                    var length = $("#myTable tbody").find(".tr-data").length;
                    if (value.trim() == "") {
                        return "成本价不能为空";
                    } else if (length == 0) {
                        if (!util.checkPrice(value)) {
                            return "请输入一个正确的价格";
                        } else if (parseFloat(value) == 0) {
                            return "请输入大于0的金额";
                        }
                    }
                },
                tradePrice : function (value) {
                    var length = $("#myTable tbody").find(".tr-data").length;
                    if (value.trim() == "") {
                        return "批发价不能为空";
                    } else if (length == 0) {
                        if (!util.checkPrice(value)) {
                            return "请输入一个正确的价格";
                        } else if (parseFloat(value) == 0) {
                            return "请输入大于0的金额";
                        }

                        var price = $("[name=price]").val();
                        if (parseFloat(value) >= parseFloat(price)) {
                            return "批发价不能大于等于售价，请重新设置";
                        }
                    }
                },
                postage : function (value) {
                    var postage = $("[name=postage]").val()
                    if (parseFloat(postage) < 0.0) {
                        $("[name=postage]").val('0.00')
                        return "邮费默认为0";
                    }
                },
                openStatus: function (value) {
                    if (value == "") {
                        return "请选择上架时间";
                    }
                },
                openStartDate: function (value) {
                    var status = $("[name=openStatus]:checked").val();
                    if (status == 2) {
                        if (value == "") {
                            return "请选择上架售卖时间";
                        } else {
                            var date = new Date();
                            var start = new Date(value.replace(/-/g, "/"));
                            if (start < date) {
                                return "上架时间不能早于今天";
                            }
                        }
                    }
                },
                content: function (value) {
                    $("#contentView").html(ue.getContent());
                    var content = $("#contentView").html();
                    if (content == "") {
                        return "请输入商品详情";
                    }
                }
            });

            //监听提交
            form.on('submit', function (data) {
                if (txzSpec.submitBefore()) {
                    submitForm(data);
                    localStorage.removeItem("myCategory");
                }
            });
        });

        $(".tag-wrap").delegate(".category-opt", "click", function (e) {
            var target = $(e.target);
            var value = $(target).closest(".tag-item").data("id");
            $(target).closest(".tag-item").remove();

            var giftJson = localStorage.getItem("myCategory");
            var _giftArray = eval(giftJson);

            var index = -1; // 如果不存在返回-1，否则返回index
            $.each(_giftArray, function (ii, dd) {
                if (value == dd.id) {
                    index = ii;
                }
            });
            _giftArray.splice(index, 1);
            localStorage.setItem("myCategory", JSON.stringify(_giftArray));
        })

        $("[name=stock]").bind("input propertychange", function (e) {
            var $this = $(e.target);
            if (!$this.prop("readonly")) {
                $(".realStock").val($this.val());
            }
        })

        $('#sel_pic_img').click(function () {
            txz.openSelImg({
                min: 1,
                max: 1,
                info: '建议尺寸：800x450',
                type: '<%=TargetType.MALL.getCode()%>',
                cb: function (imgs) {
                    $('#cover-img').css('background-image', 'url(' + imgs[0].path + ')');
                    $('#pic').val(imgs[0].path);
                }
            })
        });

        ue.addListener('ready', function () {
            this.setContent($("#contentView").html());

            if (!'${mallGoods.id}') {
                //加载缓存
                formcache = new fCache({
                    fCacheKey: 'form_cache_mallGoods',//暂存的key
                    cacheCallback: loadCacheData,//获取到缓存后加载的方法
                    getFormData: getFormData
                }).init();
            }
        });

        ue.addListener('blur', function () {
            $("#contentView").html(ue.getContent());
        });

        // 拖拽排序
        sortable();
    });

    function submitForm(data) {
        txz.submitObject(data.elem, function (callBack) {
            $("#content").val(ue.getContent().replace(/&quot;/gi, ""));
            var formData = getFormData();
            var action = $("#myForm").attr("action");
            txz.ajaxRequest({
                method: 'post',
                url: action,
                saveCache: true,
                cacheObj: formcache,
                params: formData,
                callBack: function (res) {
                    typeof callBack === 'function' && callBack();
                    if (res.success) {
                        if ($(data.elem).hasClass('preview-btn')) {
                            if ('${empty mallGoods.id}' === 'true') {
                                location.href = '${ctx}/mall/goods/view.do?id=' + res.data;
                            } else {
                                var $previewFrame = $($('.preview-box').find('iframe')[0].contentWindow.document).find('iframe');
                                $previewFrame.attr('src', $previewFrame.attr('src'));
                            }
                        } else {
                            util.layerMsgSuccess("提交成功", function () {
                                location.href = "${ctx}/mall/goods/list.do";
                            });
                        }
                    } else {
                        util.layerMsgError("提交失败")
                    }
                }
            });
        })
    }


    //此方法用于加载缓存数据
    function loadCacheData(cacheData) {
        // 商品图片
        if (cacheData['picList']) {
            var picList = cacheData['picList'].split(",");
            for (var i = 0; i < picList.length; i++) {
                var item = picList[i];
                $("#img_list").append('<div class="item" data-url="' + item + '">' +
                    '<div class="img-item" style="background-image: url(' + item + ')">' +
                    '<span class="icon-close-new" style="right: -11px; top: -13px;" onclick="delQImg(this)"></span>' +
                    '</div>' +
                    '</div>');
            }
        }
        // 商品视频
        if (cacheData['videoList']) {
            var videoList = cacheData['videoList'];
            if (util.isValid(videoList)) {
                $("#vide_code").val(videoList);
            }
        }

        // 商品分类
        if (cacheData['categoryCache']) {
            var categoryList = eval(cacheData['categoryCache']);
            var _contentArray = new Array();
            for (var i = 0; i < categoryList.length; i++) {
                _contentArray.push('<div class="tag-item" data-id="' + categoryList[i].id + '">');
                _contentArray.push('<span class="tag-name">' + categoryList[i].name + '</span>');
                _contentArray.push('<i class="iconfont icon-close category-opt"></i>');
                _contentArray.push('</div>');
            }
            var $content = $(".tag-wrap");
            $content.html(_contentArray.join(""));
        }

        if (cacheData['specModelCache'].replace('{', '').replace('}', '') && cacheData['productCache']) {
            var specModelCache = JSON.parse(cacheData['specModelCache']);
            var productCache = JSON.parse(cacheData['productCache']);
            var results = {
                speModels: specModelCache,
                products: productCache,
                delModelList: [],
                hasSpec: true
            };
            txzSpec.initPlugin();
            txzSpec.loadData(results);
        }
        form.render();
    }

    function getFormData() {
        // 封面图
        var array = new Array();
        $("#img_list .item").each(function (index, element) {
            array.push($(element).attr("data-url"));
        });
        if (array.length > 0) {
            $("#picList").val(array.join(","));
        }

        // 视频
        $("#videoList").val($(".video-link").val());

        // 分类
        var _giftArray = new Array();
        var _categoryArray = new Array();
        $(".tag-wrap .tag-item").each(function (index, elem) {
            var tagId = $(elem).data("id");
            var tagName = $(elem).find(".tag-name").text();
            _giftArray.push(tagId);
            var map = {
                id: tagId,
                name: tagName
            };
            _categoryArray.push(map);
        });
        if (_giftArray.length > 0) {
            $("#categoryIds").val(_giftArray.join(","));
            $("[name=categoryCache]").val(JSON.stringify(_categoryArray));
        }

        getSpecFormData();
        getProductFormData();

        $("#content").val(ue.getContent().replace(/&quot;/gi, ""));
        return util.serializeForm($('#myForm').serializeArray());
    }

    // 缓存规格数据
    function getSpecFormData() {
        var specMap = {};
        $(".sku-container").find(".rc-sku-group").each(function (pIndex, pEle) {
            var modelId = $(pEle).attr('data-model');
            var chk = $(pEle).find('[type=checkbox]').prop('checked');


            specMap[modelId] = {};
            specMap[modelId].id = modelId;
            specMap[modelId].name = $(pEle).find(".spec-name").val();
            specMap[modelId].sort = pIndex + 1;
            specMap[modelId].specPicFlag = chk ? 1 : 0;
            specMap[modelId].subModelId = [];
            specMap[modelId].subModelName = [];
            specMap[modelId].subModelPic = [];
            specMap[modelId].subModelSort = [];

            $(pEle).find(".sub-item").each(function (cIndex, cEle) {
                var subName = $(cEle).find(".sub-item-text :input").val();
                if (!util.isValid(subName)) {
                    return true;
                }
                var subId = $(cEle).attr("data-new-id") || '';
                var subPic = $(cEle).find("[name=pic]").val() || '';

                specMap[modelId].subModelId.push(subId);
                specMap[modelId].subModelName.push(subName);
                specMap[modelId].subModelPic.push(subPic);
                specMap[modelId].subModelSort.push(cIndex + 1);
            })
        });
        $("[name=specModelCache]").val(JSON.stringify(specMap));
        console.log(JSON.stringify(specMap));
    }

    // 缓存产品数据
    function getProductFormData() {
        var productList = [];
        $("#myTable tbody").find(".tr-data").each(function (i, tr) {
            var _modelArray = [];
            $(tr).find(".spec-value").each(function (k, input) {
                _modelArray.push($(input).attr('data-model'));
            });

            var map = {
                imgUrl: $(tr).find(".spec-value-pic").val() || '',
                model: _modelArray.join(','),
                price: $(tr).find(".spec-price").val() || '',
                productId: $(tr).attr("data-productId"),
                salesNum: 0,
                stock: $(tr).find(".spec-stock").val() || '',
                realStock: $(tr).find(".spec-stock").val() || ''
            };

            productList.push(map);
        });
        $("[name=productCache]").val(JSON.stringify(productList));
        console.log(JSON.stringify(productList));
    }

    // 文本编辑器图片上传
    function uEditorUploadCI(editor) {
        txz.openSelImg({
            min: 1,
            type: '<%=TargetType.MALL.getCode()%>',
            cb: function (imgs) {
                if (imgs.length) {
                    for (var i = 0, item; i < imgs.length; i++) {
                        item = imgs[i];
                        editor.focus();
                        editor.execCommand('inserthtml', item.htmlStr);
                    }
                }
            }
        })
    }

    function uEditorUploadCIVideo(editor) {
        txz.openSelVideo({
            min: 1,
            type: '<%=TargetType.MALL.getCode()%>',
            cb: function (imgs) {
                if (imgs.length) {
                    for (var i = 0, item; i < imgs.length; i++) {
                        item = imgs[i];
                        editor.focus();
                        editor.execCommand('inserthtml', item.htmlStr);
                    }
                }
            }
        })
    }

    function openUploadCI() {
        var picLength = $(".ci-img-list .item").length;
        var maxLength = maxNum - picLength <= 0 ? 0 : maxNum - picLength;
        txz.openSelImg({
            min: 1,
            max: maxLength,
            type: '<%=TargetType.MALL.getCode()%>',
            cb: function (imgs) {
                if (imgs.length) {
                    for (var i = 0, item; i < imgs.length; i++) {
                        item = imgs[i];
                        $("#img_list").append('<div class="item" data-url="' + item.path + '">' +
                            '<div class="img-item" style="background-image: url(' + item.path + ')">' +
                            // '<i class="layui-icon del-icon" onclick="delQImg(\'' + item.path + '\',this, \'\')">&#x1007;</i>' +
                            '<span class="icon-close-new" style="right: -11px; top: -13px;" onclick="delQImg(this)"></span>' +
                            '</div>' +
                            '</div>');
                    }
                }
                var imgLength = $("#img_list .item").length;
                if (imgLength == maxNum) {
                    $(".addPicBtn").prop('disabled', true);
                }
            }
        })
    }

    function delQImg(obj) {
        $(obj).closest(".item").remove();
        var imgLength = $("#img_list .item").length;
        if (imgLength < maxNum) {
            $(".addPicBtn").prop('disabled', false);
        }
    }

    function openUploadVideo() {
        txz.openSelVideo({
            min: 1,
            max: 1,
            backVideoOrIframe: 'video',
            type: '<%=TargetType.MALL.getCode()%>',
            cb: function (imgs) {
                if (imgs.length) {
                    for (var i = 0, item; i < imgs.length; i++) {
                        item = imgs[i];
                        $("#vide_code").val(item.htmlStr);
                    }
                }
            }
        })
    }

    function clearValue() {
        $("#vide_code").val("");
    }

    function selectCategory() {
        function cb($jquery) {
            var categoryIds = $($jquery.find("#categoryIds")).val();
            var categoryNames = $($jquery.find("#categoryNames")).val();
            var _idsArray = categoryIds.split(",");
            var _namesArray = categoryNames.split(",");
            var _contentArray = new Array();
            for (var i = 0; i < _idsArray.length; i++) {
                _contentArray.push('<div class="tag-item" data-id="' + _idsArray[i] + '">');
                _contentArray.push('<span class="tag-name">' + _namesArray[i] + '</span>');
                _contentArray.push('<i class="iconfont icon-close category-opt"></i>');
                _contentArray.push('</div>');
            }
            var $content = $(".tag-wrap");
            $content.html(_contentArray.join(""));
        }

        var _giftArray = new Array();
        $(".tag-wrap .tag-item").each(function (index, elem) {
            var giftId = $(elem).data("id");
            _giftArray.push(giftId);
        });
        var categoryIds = _giftArray.join(",");
        openDialog('选择分类', '${ctx}/mall/category/selectCategory.do?isMulti=2&categoryIds=' + categoryIds, '650px', '550px', cb);
    }

    function openDialog(title, url, width, height, cb, target) {
        layer.open({
            type: 2,
            area: [width, height],
            title: title,
            maxmin: true, //开启最大化最小化按钮
            content: url,
            btn: ['确定', '关闭'],
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index);
                var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                var inputForm = body.find('#inputForm');
                var top_iframe;
                if (target) {
                    top_iframe = target;//如果指定了iframe，则在改frame中跳转
                } else {
                    top_iframe = '_parent';//获取当前active的tab的iframe
                }
                inputForm.attr("target", top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示

                if (iframeWin.contentWindow.doSubmit()) {
                    cb(iframeWin.contentWindow.$);

                    setTimeout(function () {
                        top.layer.close(index);
                    }, 100);//延时0.1秒，对应360 7.1版本bug
                }

            },
            cancel: function (index) {
            }
        });
    }

    function sortable() {
        $("#img_list").sortable({
            items : ".item",
            placeholder: 'sortable-placeholder',
            opacity: 0.5,
            forcePlaceholderSize: true
        });
        $(".carousel-list").disableSelection();
    }
</script>
</body>
</html>